package com.cbs.android.module.userkit.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.cbs.android.component.application.activity.CBSActivity;
import com.cbs.android.component.application.activity.CBSDialogFragment;
import com.cbs.android.component.application.activity.handler.CBSSimpleActivityResultHandler;
import com.cbs.android.component.applicationutils.network.ErrorResponse;
import com.cbs.android.component.graphicsutils.GraphicsUtils;
import com.cbs.android.component.log.L;
import com.cbs.android.component.sensitivewords.SensitiveWords;
import com.cbs.android.component.toast.Toast;
import com.cbs.android.extension.glide.target.RoundedImageViewTarget;
import com.cbs.android.extension.glide.urlloader.qiniu.QiniuUrlLoader;
import com.cbs.android.extension.glide.urlloader.qiniu.url.AvatarUrl;
import com.cbs.android.extension.glide.urlloader.qiniu.url.LimitShortUrl;
import com.cbs.android.function.capture.CaptureFunction;
import com.cbs.android.function.capture.CaptureHandler;
import com.cbs.android.function.imagecrop.ImageCropFunction;
import com.cbs.android.function.imagecrop.ImageCropHandler;
import com.cbs.android.function.imagepick.ImagePickFunction;
import com.cbs.android.function.imagepick.ImagePickHandler;
import com.cbs.android.function.input.ButtonDialogFragment;
import com.cbs.android.function.input.DatePickDialogFragment;
import com.cbs.android.function.input.InputDialogFragment;
import com.cbs.android.function.input.SelectDialogFragment;
import com.cbs.android.module.user.user.UserModule;
import com.cbs.android.module.user.user.entity.User;
import com.cbs.android.module.user.user.handler.ModuleHandler;
import com.cbs.android.module.userkit.R;
import com.cbs.android.module.userkit.UserKit;
import com.cbs.android.module.userkit.UserKitSetting;
import com.google.gson.Gson;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by broche on 11/11/15.
 */
public class InformationActivity extends CBSActivity implements View.OnClickListener, ButtonDialogFragment.OnButtonListener {
    private static final String TAG = InformationActivity.class.getName();
    private int imageChooseType = 0; // 0-avatar 1-homeImage
    private TextView nickNameView;
    private TextView realNameView;
    private TextView sexView;
    private TextView birthdayView;
    private ImageView avatarView;
    private ImageView homeImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setResult(RESULT_CANCELED);

        super.setContentView(R.layout.cbs_userkit_activity_information);

        nickNameView = (TextView) findViewById(R.id.cbs_userkit_information_nickname);
        realNameView = (TextView) findViewById(R.id.cbs_userkit_information_realname);
        sexView = (TextView) findViewById(R.id.cbs_userkit_information_sex);
        birthdayView = (TextView) findViewById(R.id.cbs_userkit_information_birthday);
        avatarView = (ImageView) findViewById(R.id.cbs_userkit_information_avatar);
        homeImageView = (ImageView) findViewById(R.id.cbs_userkit_information_homeimage);

        findViewById(R.id.cbs_userkit_information_back).setOnClickListener(this);
        findViewById(R.id.cbs_userkit_information_nicknameclick).setOnClickListener(this);
        findViewById(R.id.cbs_userkit_information_realnameclick).setOnClickListener(this);
        findViewById(R.id.cbs_userkit_information_sexclick).setOnClickListener(this);
        findViewById(R.id.cbs_userkit_information_birthdayclick).setOnClickListener(this);
        findViewById(R.id.cbs_userkit_information_avatarclick).setOnClickListener(this);
        findViewById(R.id.cbs_userkit_information_homeimageclick).setOnClickListener(this);
        findViewById(R.id.cbs_userkit_information_qrcodeclick).setOnClickListener(this);
        findViewById(R.id.cbs_userkit_information_modifyusernameclick).setOnClickListener(this);
        findViewById(R.id.cbs_userkit_information_modifypasswordclick).setOnClickListener(this);
        findViewById(R.id.cbs_userkit_information_logout).setOnClickListener(this);

        User user = UserModule.getUser();
        if (user == null) {
            Intent intent = new Intent();
            intent.putExtra(UserKit.IntentMessage, getString(R.string.cbs_userkit_verify_unregistered));
            setResult(RESULT_CANCELED, intent);
            finish();
            return;
        }

        nickNameView.setText(user.getNickName());
        realNameView.setText(user.getRealName());
        sexView.setText(user.getSex() == 0 ? getString(R.string.cbs_userkit_sex_female) : getString(R.string.cbs_userkit_sex_male));
        birthdayView.setText(user.getBirthday());

        String avatarUrl = user.getAvatar();
        String homeImageUrl = user.getHomeImage();
        if (UserKitSetting.getImagePathTranslator() != null) {
            avatarUrl = UserKitSetting.getImagePathTranslator().avatarPath(avatarUrl);
            homeImageUrl = UserKitSetting.getImagePathTranslator().homeImagePath(homeImageUrl);
        }
        Glide.with(this).using(new QiniuUrlLoader(this)).load(new AvatarUrl(avatarUrl)).asBitmap().error(R.drawable.cbs_userkit_defaultavatar).into(new RoundedImageViewTarget(avatarView));
        Glide.with(this).using(new QiniuUrlLoader(this)).load(new LimitShortUrl(homeImageUrl)).into(homeImageView);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.cbs_userkit_information_back) {
            finish();
        } else if (v.getId() == R.id.cbs_userkit_information_avatarclick) {
            imageChooseType = 0;
            new ButtonDialogFragment()
                    .setTitle(getString(R.string.cbs_userkit_picture_title))
                    .setItems(Arrays.asList(getResources().getStringArray(R.array.cbs_userkit_picture_items)))
                    .show(getSupportFragmentManager(), "avatar");
        } else if (v.getId() == R.id.cbs_userkit_information_homeimageclick) {
            imageChooseType = 1;
            new ButtonDialogFragment()
                    .setTitle(getString(R.string.cbs_userkit_picture_title))
                    .setItems(Arrays.asList(getResources().getStringArray(R.array.cbs_userkit_picture_items)))
                    .show(getSupportFragmentManager(), "homeimage");
        } else if (v.getId() == R.id.cbs_userkit_information_nicknameclick) {
            try {
                UserKitSetting.getNicknameDialogFragmentClass().newInstance()
                        .setTitle(getString(R.string.cbs_userkit_dialog_title_nickname))
                        .setDesc(getString(R.string.cbs_userkit_dialog_desc_nickname))
                        .setContent(UserModule.getUser() == null ? "" : UserModule.getUser().getNickName())
                        .setOnConfirmListener(new InputDialogFragment.OnConfirmListener() {
                            @Override
                            public void onConfirm(CBSDialogFragment cbsDialogFragment, String content) {
                                String word = SensitiveWords.verify(content);
                                if (!StringUtils.isEmpty(word)) {
                                    Toast.show(String.format(getString(R.string.cbs_userkit_hint_sensitivewords), word));
                                    return;
                                }
                                for (String filterKey : UserKitSetting.getNicknameFilterKeywords()) {
                                    if (StringUtils.contains(content, filterKey)) {
                                        Toast.show(String.format(getString(R.string.cbs_userkit_hint_filterkeys), filterKey));
                                        return;
                                    }
                                }
                                try {
                                    if (!StringUtils.isEmpty(content)) {
                                        cbsDialogFragment.dismiss();
                                        for (int i = 15; i <= content.length(); i++) {
                                            if (content.substring(0, i).getBytes("gbk").length > 30) {
                                                content = content.substring(0, i - 1);
                                                break;
                                            }
                                        }
                                        User user = new User().setNickName(content);
                                        UserModule.setUserInformation(user, new ModuleHandler<User>() {
                                            @Override
                                            public void onSuccess(User entity) {
                                                Toast.show(getString(R.string.cbs_userkit_hint_modifySuccess));
                                                nickNameView.setText(entity.getNickName());
                                            }

                                            @Override
                                            public void onFailure(int code, String message) {
                                                Toast.show(getString(R.string.cbs_userkit_hint_modifyFailure));
                                            }

                                            @Override
                                            public void onException(Exception exception) {
                                                Toast.show(getString(R.string.cbs_userkit_hint_modifyFailure));
                                            }
                                        });
                                    } else {
                                        Toast.show(getString(R.string.cbs_userkit_verify_emptynickname));
                                        return;
                                    }
                                } catch (UnsupportedEncodingException e) {
                                    Toast.show(getString(R.string.cbs_userkit_hint_modifyFailure));
                                    return;
                                }
                            }
                        }).show(getSupportFragmentManager(), "nickname");
            } catch (Exception e) {
                L.e(TAG, "", e);
                Toast.show(getString(R.string.cbs_userkit_hint_modifyFailure));
            }
        } else if (v.getId() == R.id.cbs_userkit_information_realnameclick) {
            try {
                UserKitSetting.getRealnameDialogFragmentClass().newInstance()
                        .setTitle(getString(R.string.cbs_userkit_dialog_title_realname))
                        .setContent(UserModule.getUser() == null ? "" : UserModule.getUser().getRealName())
                        .setOnConfirmListener(new InputDialogFragment.OnConfirmListener() {
                            @Override
                            public void onConfirm(CBSDialogFragment cbsDialogFragment, String str) {
                                if (!StringUtils.isEmpty(str)) {
                                    cbsDialogFragment.dismiss();
                                    User user = new User().setRealName(str);
                                    UserModule.setUserInformation(user, new ModuleHandler<User>() {
                                        @Override
                                        public void onSuccess(User entity) {
                                            Toast.show(getString(R.string.cbs_userkit_hint_modifySuccess));
                                            realNameView.setText(entity.getRealName());
                                        }

                                        @Override
                                        public void onFailure(int code, String message) {
                                            Toast.show(getString(R.string.cbs_userkit_hint_modifyFailure));
                                        }

                                        @Override
                                        public void onException(Exception exception) {
                                            Toast.show(getString(R.string.cbs_userkit_hint_modifyFailure));
                                        }
                                    });
                                } else {
                                    Toast.show(getString(R.string.cbs_userkit_hint_modifyFailure));
                                }
                            }
                        }).show(getSupportFragmentManager(), "realname");
            } catch (Exception e) {
                L.e(TAG, "", e);
                Toast.show(getString(R.string.cbs_userkit_hint_modifyFailure));
            }
        } else if (v.getId() == R.id.cbs_userkit_information_sexclick) {
            try {
                final List<String> items = new ArrayList<>();
                items.add(getString(R.string.cbs_userkit_sex_female));
                items.add(getString(R.string.cbs_userkit_sex_male));
                UserKitSetting.getSexDialogFragmentClass().newInstance()
                        .setTitle(getString(R.string.cbs_userkit_dialog_title_sex))
                        .setItems(items)
                        .setSelecter(UserModule.getUser() == null ? "" : items.get(UserModule.getUser().getSex()))
                        .setOnConfirmListener(new SelectDialogFragment.OnConfirmListener() {
                            @Override
                            public void onConfirm(CBSDialogFragment cbsDialogFragment, final int index, String s) {
                                cbsDialogFragment.dismiss();
                                User user = new User();
                                user.setSex(index);
                                UserModule.setUserInformation(user, new ModuleHandler<User>() {
                                    @Override
                                    public void onSuccess(User entity) {
                                        sexView.setText(items.get(index));
                                        Toast.show(getString(R.string.cbs_userkit_hint_modifySuccess));
                                    }

                                    @Override
                                    public void onFailure(int code, String message) {
                                        Toast.show(getString(R.string.cbs_userkit_hint_modifyFailure));
                                    }

                                    @Override
                                    public void onException(Exception exception) {
                                        Toast.show(getString(R.string.cbs_userkit_hint_modifyFailure));
                                    }
                                });
                            }
                        }).show(getSupportFragmentManager(), "sex");
            } catch (Exception e) {
                L.e(TAG, "", e);
                Toast.show(getString(R.string.cbs_userkit_hint_modifyFailure));
            }
        } else if (v.getId() == R.id.cbs_userkit_information_birthdayclick) {
            try {
                UserKitSetting.getBirthdayDialogFragmentClass().newInstance()
                        .setTitle(getString(R.string.cbs_userkit_dialog_title_birthday))
                        .setBirthday(UserModule.getUser() == null ? "" : UserModule.getUser().getBirthday())
                        .setOnConfirmListener(new DatePickDialogFragment.OnConfirmListener() {
                            @Override
                            public void onConfirm(CBSDialogFragment dialogFragment, String birthday) {
                                if (!StringUtils.isEmpty(birthday)) {
                                    dialogFragment.dismiss();
                                    User user = new User().setBirthday(birthday);
                                    UserModule.setUserInformation(user, new ModuleHandler<User>() {
                                        @Override
                                        public void onSuccess(User entity) {
                                            Toast.show(getString(R.string.cbs_userkit_hint_modifySuccess));
                                            birthdayView.setText(entity.getBirthday());
                                        }

                                        @Override
                                        public void onFailure(int code, String message) {
                                            Toast.show(getString(R.string.cbs_userkit_hint_modifyFailure));
                                        }

                                        @Override
                                        public void onException(Exception exception) {
                                            Toast.show(getString(R.string.cbs_userkit_hint_modifyFailure));
                                        }
                                    });
                                } else {
                                    Toast.show(getString(R.string.cbs_userkit_hint_modifyFailure));
                                }
                            }
                        }).show(getSupportFragmentManager(), "birthday");
            } catch (Exception e) {
                L.e(TAG, "", e);
                Toast.show(getString(R.string.cbs_userkit_hint_modifyFailure));
            }
        } else if (v.getId() == R.id.cbs_userkit_information_qrcodeclick) {
            UserKit.qrcode(this, new CBSSimpleActivityResultHandler() {
                @Override
                public void onSuccess(int i, Intent intent) {
                    // do nothing
                }

                @Override
                public void onCancel(int i, Intent data) {
                    if (data != null && data.hasExtra(UserKit.IntentMessage)) {
                        Toast.show(data.getStringExtra(UserKit.IntentMessage));
                    } else {
                        // do nothing
                    }
                }
            });
        } else if (v.getId() == R.id.cbs_userkit_information_modifyusernameclick) {
            UserKit.modifyUserName(this, new CBSSimpleActivityResultHandler() {
                @Override
                public void onSuccess(int requestCode, Intent data) {
                    Toast.show(getString(R.string.cbs_userkit_hint_modifySuccess));
                }

                @Override
                public void onCancel(int requestCode, Intent data) {
                    if (data != null && data.hasExtra(UserKit.IntentMessage)) {
                        Toast.show(data.getStringExtra(UserKit.IntentMessage));
                    } else {
                        // do nothing
                    }
                }
            });
        } else if (v.getId() == R.id.cbs_userkit_information_modifypasswordclick) {
            UserKit.modifyPassword(this, new CBSSimpleActivityResultHandler() {
                @Override
                public void onSuccess(int requestCode, Intent data) {
                    Toast.show(getString(R.string.cbs_userkit_hint_modifySuccess));
                }

                @Override
                public void onCancel(int requestCode, Intent data) {
                    if (data != null && data.hasExtra(UserKit.IntentMessage)) {
                        Toast.show(data.getStringExtra(UserKit.IntentMessage));
                    } else {
                        // do nothing
                    }
                }
            });
        } else if (v.getId() == R.id.cbs_userkit_information_logout) {

            UserModule.logout(new ModuleHandler<User>() {
                @Override
                public void onSuccess(User user) {
                    finish();
                }

                @Override
                public void onFailure(int code, String message) {
                    try {
                        ErrorResponse errorResponse = new Gson().fromJson(message, ErrorResponse.class);
                        Toast.show(errorResponse.getErrorMsg());
                    } catch (Exception e) {
                        Toast.show(getString(R.string.cbs_userkit_hint_logoutFailure));
                    }
                    L.w(TAG, "code: " + code + "\tmessage: " + message);
                }

                @Override
                public void onException(Exception e) {
                    Toast.show(getString(R.string.cbs_userkit_hint_logoutFailure));
                    L.w(TAG, "", e);
                }
            });
        }
    }

    @Override
    public void onButtonClick(CBSDialogFragment cbsDialogFragment, int index, String s) {
        if (index == 0) {
            CaptureFunction.startImageCapture(this, captureHandler);
        } else if (index == 1) {
            ImagePickFunction.start(this, imagePickHandler);
        }
    }

    private CaptureHandler captureHandler = new CaptureHandler() {
        @Override
        public void onCaptureSuccess(int i, Intent intent, Uri uri) {
            if (imageChooseType == 0) {
                ImageCropFunction.start(InformationActivity.this, uri,
                        UserKitSetting.getAvatarWidth(), UserKitSetting.getAvatarHeight(),
                        UserKitSetting.getAvatarWidth(), UserKitSetting.getAvatarHeight(),
                        imageCropHandler);
            } else {
                ImageCropFunction.start(InformationActivity.this, uri,
                        UserKitSetting.getHomeImageWidth(), UserKitSetting.getHomeImageHeight(),
                        UserKitSetting.getHomeImageWidth(), UserKitSetting.getHomeImageHeight(),
                        imageCropHandler);
            }
        }

        @Override
        public void onCancel(int i, Intent intent) {
            // do nothing
        }
    };


    private ImagePickHandler imagePickHandler = new ImagePickHandler() {
        @Override
        public void onPickSuccess(int i, Intent intent, List<Uri> list) {
            if (imageChooseType == 0) {
                ImageCropFunction.start(InformationActivity.this, list.get(0),
                        UserKitSetting.getAvatarWidth(), UserKitSetting.getAvatarHeight(),
                        UserKitSetting.getAvatarWidth(), UserKitSetting.getAvatarHeight(),
                        imageCropHandler);
            } else {
                ImageCropFunction.start(InformationActivity.this, list.get(0),
                        UserKitSetting.getHomeImageWidth(), UserKitSetting.getHomeImageHeight(),
                        UserKitSetting.getHomeImageWidth(), UserKitSetting.getHomeImageHeight(),
                        imageCropHandler);
            }
        }

        @Override
        public void onCancel(int i, Intent intent) {
            // do nothing
        }
    };

    private ImageCropHandler imageCropHandler = new ImageCropHandler() {
        @Override
        public void onCropSuccess(int i, Intent intent, Uri uri) {
            Bitmap bitmap = GraphicsUtils.loadBitmap(uri.getPath());
            if (imageChooseType == 0) {
                avatarView.setImageDrawable(null);
                UserModule.setUserAvatar(bitmap, moduleHandler);
            } else {
                homeImageView.setImageDrawable(null);
                UserModule.setUserHomeImage(bitmap, moduleHandler);
            }
        }

        @Override
        public void onCancel(int i, Intent intent) {
            // do nothing
        }
    };

    private ModuleHandler<User> moduleHandler = new ModuleHandler<User>() {
        @Override
        public void onSuccess(User user) {
            Toast.show(getString(R.string.cbs_userkit_hint_modifySuccess));
            if (imageChooseType == 0) {
                String avatarUrl = user.getAvatar();
                if (UserKitSetting.getImagePathTranslator() != null) {
                    avatarUrl = UserKitSetting.getImagePathTranslator().avatarPath(avatarUrl);
                }
                Glide.with(InformationActivity.this).using(new QiniuUrlLoader(InformationActivity.this)).load(new AvatarUrl(avatarUrl)).asBitmap().error(R.drawable.cbs_userkit_defaultavatar).into(new RoundedImageViewTarget(avatarView));
            } else {
                String homeImageUrl = user.getHomeImage();
                if (UserKitSetting.getImagePathTranslator() != null) {
                    homeImageUrl = UserKitSetting.getImagePathTranslator().homeImagePath(homeImageUrl);
                }
                Glide.with(InformationActivity.this).using(new QiniuUrlLoader(InformationActivity.this)).load(new LimitShortUrl(homeImageUrl)).into(homeImageView);
            }
        }

        @Override
        public void onFailure(int code, String message) {
            Toast.show(getString(R.string.cbs_userkit_hint_modifyFailure));
            L.e(TAG, String.format("code: %d\tmessage: %s", code, message));
        }

        @Override
        public void onException(Exception e) {
            Toast.show(getString(R.string.cbs_userkit_hint_modifyFailure));
            L.e(TAG, "", e);
        }
    };
}
